package 尚硅谷;

import java.util.concurrent.*;

/**
 * @author zhangmin
 * @create 2022-03-24 16:00
 */


public class MyThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService threadPool=new ThreadPoolExecutor(2,5,1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());
        //new ThreadPoolExecutor.AbortPolicy()拒绝策略为直接报错
        //new ThreadPoolExecutor.CallerRunsPolicy()不会报错，直接退回到调用者线程
        //new ThreadPoolExecutor.DiscardOldestPolicy()抛弃等待最久的线程
        //new ThreadPoolExecutor.DiscardPolicy()直接丢弃任务，不予任何处理也不抛出异常，如果运行任务丢失，这是一种好方案
        try {
            for (int i = 0; i < 9; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }


    public static void threadPoolInit(){
        //FixedThreadPool：固定线程数
        //ExecutorService threadPool= Executors.newFixedThreadPool(3);
        //SingleThreadExecutor：创建一个只有一个线程的线程池
        //ExecutorService threadPool= Executors.newSingleThreadExecutor();
        //创建一个拥有N个线程的线程池，根据调度创建合适的线程
        ExecutorService threadPool= Executors.newCachedThreadPool();

        //模拟10个用户来办理业务，每个用户就是一个来自外部请求线程
        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                });
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
